package com.jzlin.funhub.admin.service.article;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzlin.funhub.admin.common.consts.RedisConst;
import com.jzlin.funhub.admin.mapper.ArticleTagMapper;
import com.jzlin.funhub.admin.model.entity.ArticleTag;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 文章标签表 服务实现类
 * </p>
 *
 * @author jzlin
 * @since 2025-09-04
 */
@Service
public class ArticleTagService extends ServiceImpl<ArticleTagMapper, ArticleTag> {
    @Autowired
    private RedissonClient redissonClient;

    /**
     * 根据名称获取标签
     * @param tags
     */
    public List<ArticleTag> getTagsByName(List<String> tags) {
        List<ArticleTag> result = this.query().in("name", tags).list();
        // 已存在的标签
        List<String> existTags = result.stream().map(ArticleTag::getName).collect(Collectors.toList());
        // 不存在的标签
        List<String> notExistTags = tags.stream().filter(t -> !existTags.contains(t)).collect(Collectors.toList());

        // 新建tag，使用分布式锁
        RLock lock =redissonClient.getLock(RedisConst.LOCK_KEY.ARTICLES_TAG);
        try {
            lock.lock();
            for (String t : notExistTags) {
                ArticleTag tag = getOrCreateTag(t);
                result.add(tag);
            }
        } finally {
            lock.unlock();
        }
        return result;
    }

    /**
     * 根据名称获取标签，没有则创建
     * @param tagName
     * @return
     */
    public ArticleTag getOrCreateTag(String tagName) {
        ArticleTag tag = this.query().eq("name", tagName).one();
        if (tag == null) {
            tag = new ArticleTag();
            tag.setName(tagName);
            this.save(tag);
        }
        return tag;
    }
}
